#pragma once


namespace p2pms 
{

template<typename T>
class Vector 
{
public:
    Vector() : data(nullptr), size(0), capacity(0) {}
    ~Vector() { clear(); free(data); }

    void push_back(const T& value) {
        if (size == capacity) {
            reserve(capacity == 0 ? 4 : capacity * 2);
        }
        new(&data[size]) T(value);
        ++size;
    }
    void reserve(size_t new_cap) {
        if (new_cap <= capacity) return;
        T* new_data = (T*)malloc(sizeof(T) * new_cap);
        for (size_t i = 0; i < size; ++i) {
            new(&new_data[i]) T(data[i]);
            data[i].~T();
        }
        free(data);
        data = new_data;
        capacity = new_cap;
    }
    void resize(size_t new_size) {
        if (new_size < size) {
            for (size_t i = new_size; i < size; ++i) data[i].~T();
        } else if (new_size > capacity) {
            reserve(new_size);
            for (size_t i = size; i < new_size; ++i) new(&data[i]) T();
        }
        size = new_size;
    }
    void clear() {
        for (size_t i = 0; i < size; ++i) data[i].~T();
        size = 0;
    }
    T& operator[](size_t i) { assert(i < size); return data[i]; }
    const T& operator[](size_t i) const { assert(i < size); return data[i]; }
    bool empty() const { return size == 0; }

private:
    T* data;
    size_t size;
    size_t capacity;
};

} // namespace p2pms